package ui.fragment.intersionfragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import Dailog.ListDialog;
import application.App;
import base.BaseBean;
import base.fragment.BaseNetFragment;
import bean.SubjectBean;
import bean.TeacherBean;
import event.IntersionEvent;
import event.IntersionLeftEvent;
import jp.wasabeef.richeditor.RichEditor;
import student.andlei.com.student.R;
import ui.activity.AddWacomActivity;
import utils.GsonUtils;
import utils.QiniuUploadUtils;
import utils.SPUtils;

/**
 * author : ChenHuiMing
 * date : 2018/9/15
 * email : 907399255@qq.com
 * description : 问答追问
 */
public class IntersionAddFragment extends BaseNetFragment {

    public static final String SUBJECT_URL = "/Qa/subject";
    public static final String TEACHER_URL = "/Qa/teacher";
    public static final String QUESTIONS_URL = "/Qa/addQa";

    private TextView mTvSubject;
    private TextView mTvTeacher;
    private RichEditor mEtProblem;
    private String mSubjectId;
    private String mTeacherId;
    private ListDialog mSubjectDailog;
    private ListDialog mTeacherDailog;


    public static IntersionAddFragment getInstance() {
        return new IntersionAddFragment();
    }

    @Override
    public void success(String action, BaseBean baseBean) {
        if (TextUtils.equals(action, SUBJECT_URL)) {
            SubjectBean detailBean = (SubjectBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), SubjectBean.class);
            chooseSubjectDialog(detailBean.list);
        } else if (TextUtils.equals(action, TEACHER_URL)) {
            TeacherBean detailBean = (TeacherBean) GsonUtils.JSONToObject(GsonUtils.beanToJSONString(baseBean.data), TeacherBean.class);
            chooseTeacherDialog(detailBean.list);
        } else if (TextUtils.equals(QUESTIONS_URL, action)) {
            if (baseBean.code == 200) {
                mEtProblem.setHtml("");
                mTvSubject.setText("");
                mTvTeacher.setText("");
                Toast.makeText(context, getResources().getString(R.string.questions_successfully), Toast.LENGTH_LONG).show();
                //提问成功 左边未解答要刷新
                IntersionLeftEvent intersionLeftEvent = new IntersionLeftEvent();
                intersionLeftEvent.isRefresh = true;
                intersionLeftEvent.leftType = IntersionLeftEvent.TYPE_NO;
                EventBus.getDefault().post(intersionLeftEvent);

            }
            onClick(getView(R.id.tv_back));
        }
    }

    @Override
    public void error(String action, Throwable e) {
        Toast.makeText(context, "网络请求失败", Toast.LENGTH_LONG).show();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_intersion_add;
    }

    @Override
    protected void findViews() {
        mTvSubject = getView(R.id.tv_subject);
        mTvTeacher = getView(R.id.tv_teacher);
        mEtProblem = getView(R.id.et_problem);
    }

    @Override
    protected void formatViews() {
        initRichEditor();
        getView(R.id.tv_back).setOnClickListener(this);
        getView(R.id.ll_subject).setOnClickListener(this);
        getView(R.id.ll_teacher).setOnClickListener(this);
        getView(R.id.tv_submit).setOnClickListener(this);
        getView(R.id.iv_picture).setOnClickListener(this);
        getView(R.id.iv_camera).setOnClickListener(this);
        getView(R.id.iv_drawingboard).setOnClickListener(this);
    }

    @Override
    protected void formatData() {

    }


    @Override
    protected void getBundle() {

    }

    private void initRichEditor() {
        mEtProblem.setEditorFontSize(18);
        mEtProblem.setPlaceholder("请输入您要提问的问题");
        mEtProblem.setEditorFontColor(getResources().getColor(R.color.font_black));
        mEtProblem.setPadding(10, 10, 10, 10);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                IntersionEvent pageEvent = new IntersionEvent();
                pageEvent.rightPager = 0;
                pageEvent.isRightPage = true;
                EventBus.getDefault().post(pageEvent);
                break;
            case R.id.ll_subject:
                post(SUBJECT_URL, BaseBean.class, false);
                break;
            case R.id.ll_teacher:
                post(TEACHER_URL, BaseBean.class, false);
                break;
            case R.id.iv_picture:
                mEtProblem.focusEditor();
                openPhoto();
                break;
            case R.id.iv_camera:
                mEtProblem.focusEditor();
                openCamera();
                break;
            case R.id.iv_drawingboard:
                mEtProblem.focusEditor();
                jumpTo(AddWacomActivity.class, 0);
                break;
            case R.id.tv_submit:
                if (TextUtils.isEmpty(mSubjectId)) {
                    Toast.makeText(context, getResources().getString(R.string.select_subject), Toast.LENGTH_LONG).show();
                    return;
                }
                if (TextUtils.isEmpty(mTeacherId)) {
                    Toast.makeText(context, getResources().getString(R.string.select_teacher), Toast.LENGTH_LONG).show();
                    return;
                }
                String content = mEtProblem.getHtml();
                if (TextUtils.isEmpty(content)) {
                    Toast.makeText(context, getResources().getString(R.string.problem_description_hint), Toast.LENGTH_LONG).show();
                    return;
                }
                Map<String, Object> map = new HashMap();
                map.put("subject_id", mSubjectId);
                map.put("teacher_id", mTeacherId);
                map.put("content", content);
                post(QUESTIONS_URL, map, BaseBean.class, false);
                break;
        }
    }

    private List<LocalMedia> selectList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                case PictureConfig.REQUEST_CAMERA:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    LocalMedia localMedia = selectList.get(0);
                    String compressPath = localMedia.getCompressPath();

                    String qiniutoken = SPUtils.getInstance(App.getInstance()).getString("uptoken");
                    String key = System.currentTimeMillis() + "note.png";
                    QiniuUploadUtils.getInstance().uploadFile(compressPath, new QiniuUploadUtils.UploadListener() {
                        @Override
                        public void onUploadSuccess(String key) {
                            String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                            final String image = yuming + key;
                            mEtProblem.insertImage(image, "\" style=\"max-width:100%");
                            selectList.clear();
                        }

                        @Override
                        public void onUploadFail(Error error) {
                            toast("插入图片失败");
                        }
                    }, qiniutoken);
                    break;
            }
        } else if (requestCode == 0) {
            if (data != null) {
                QiniuUploadUtils.getInstance().uploadFile(data.getStringExtra("filename"), new QiniuUploadUtils.UploadListener() {
                    @Override
                    public void onUploadSuccess(String key) {
                        hideLoadDialog();
                        String yuming = SPUtils.getInstance(getActivity()).getString("domain");
                        final String image = yuming + key;
                        mEtProblem.insertImage(image, "\" style=\"max-width:100%");
                    }

                    @Override
                    public void onUploadFail(Error error) {
                        hideLoadDialog();
                        Looper.prepare();
                        toast("插入图片失败");
                        Looper.loop();
                    }
                }, SPUtils.getInstance(getActivity()).getString("uptoken"));
            }

        }
    }


    private void chooseSubjectDialog(final List<SubjectBean.ListBean> listBeans) {
        if (mSubjectDailog != null && mSubjectDailog.isShowing()) {
            mSubjectDailog.dismiss();
        }
        final List<String> list = new ArrayList<>();
        for (SubjectBean.ListBean listBean : listBeans) {
            list.add(listBean.subject_name);
        }
        mSubjectDailog = new ListDialog(getActivity(), getResources().getString(R.string.select_subject), list);
        mSubjectDailog.setListItemClickListener(new ListDialog.OnListItemClickListener() {
            @Override
            public void onItemClick(int position, String s) {
                mSubjectId = listBeans.get(position).subject_id;
                mTvSubject.setText(list.get(position));
                mSubjectDailog.dismiss();
            }
        });
        mSubjectDailog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });
        darkenBackground(0.5f);
        mSubjectDailog.showAsDropDown(mTvSubject);
    }


    private void darkenBackground(Float bgcolor) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgcolor;
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getActivity().getWindow().setAttributes(lp);
    }

    private void chooseTeacherDialog(final List<TeacherBean.ListBean> listBeans) {
        if (mTeacherDailog != null && mTeacherDailog.isShowing()) {
            mTeacherDailog.dismiss();
        }
        final List<String> list = new ArrayList<>();
        for (TeacherBean.ListBean listBean : listBeans) {
            list.add(listBean.real_name);
        }
        mTeacherDailog = new ListDialog(getActivity(), getResources().getString(R.string.select_teacher), list);
        mTeacherDailog.setListItemClickListener(new ListDialog.OnListItemClickListener() {
            @Override
            public void onItemClick(int position, String s) {
                mTeacherId = listBeans.get(position).teacher_id;
                mTvTeacher.setText(list.get(position));
                mTeacherDailog.dismiss();
            }
        });
        mTeacherDailog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                darkenBackground(1f);
            }
        });
        darkenBackground(0.5f);
        mTeacherDailog.showAsDropDown(mTvTeacher);
    }

    private void openPhoto() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(false)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void openCamera() {
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .theme(R.style.picture_default_style)
                .maxSelectNum(1)
                .minSelectNum(1)
                .selectionMode(PictureConfig.MULTIPLE)
                .previewImage(true)
                .isCamera(true)
                .enableCrop(false)
                .compress(true)
                .glideOverride(160, 160)
                .previewEggs(true)
                .withAspectRatio(1, 1)
                .hideBottomControls(false)
                .isGif(true)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(false)
                .showCropGrid(false)
                .openClickSound(false)
                .selectionMedia(selectList)
                .forResult(PictureConfig.REQUEST_CAMERA);
    }
}
